package com.ruoyi.carUserService.controller;

import com.ruoyi.carUserService.service.LoginUserService;
import com.ruoyi.carUserService.util.JwtUtil;
import com.ruoyi.carUserService.util.SmsUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginUserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginUserService loginUserService;

    @RequestMapping("/get")
    public void getCode(String phone) {
        String code = SmsUtil.createCode();
        SmsUtil.send(phone, code);
        redisTemplate.opsForValue().set(phone, code, 100, TimeUnit.MINUTES);
    }

    @RequestMapping("/user")
    public AjaxResult LoginUser(@RequestParam("phoneNumber") String phone, String code) {
        Object o = redisTemplate.opsForValue().get(phone);
        if (o == null){
            return AjaxResult.error("验证码已过期/失效");
        }else if (!o.toString().equals(code)){
            return AjaxResult.error("验证码错误");
        }else {
            Integer userId = loginUserService.LoginUser(phone);
            redisTemplate.delete(phone);
            String jwt = JwtUtil.createJWT(userId.toString());
            return AjaxResult.success("登录成功",jwt);
        }

    }
}
